package frame.laxcen.loop.demo;

import frame.laxcen.loop.BaseLoopReader;
import frame.util.ByteArrayUtil;
import frame.util.ByteUtil;
import frame.util.Ref;

public class LooperReader_Demo_3 extends BaseLoopReader {

    private int cnt;

    @Override
    protected String loop(Ref<String> pc) {

        switch(pc.get()) {

            case "loop-begin":

                readU8("FrameHeader", ByteArrayUtil::toHexString);
                readU16("ControlWord", ByteArrayUtil::toHexString);
                readU16("DataLength", (bs) -> "" + ByteUtil.byteArrayToInt(bs));

            case "pid-loop-begin":

                pc.swap("pid-loop-begin");

                // 在这里初始化 cnt  可以保证重复使用 decode 的正确性

                cnt = 0;

            case "pid":

                // 实现一个 if 语意 读取任意 2 个pid后跳出循环

                if(readP16("Pid1", (byte) 0x01, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return pc.swap("pid-loop-body").get();

                if(readP16("Pid2", (byte) 0x02, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return pc.swap("pid-loop-body").get();

                if(readP16("Pid3", (byte) 0x03, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return pc.swap("pid-loop-body").get();

                if(readP16("Pid4", (byte) 0x04, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return pc.swap("pid-loop-body").get();

            case "pid-loop-end":

                pc.swap("pid-loop-end");
        }

        return pc.swap("loop-end").get();
    }
}
